import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.Queue;

public class JobHandler2 implements IJobHandler,Runnable 
{
	protected volatile Boolean running = null;
	protected volatile IServerClusterUsageData sC_UsageData = null;
	protected volatile IServerCluster serverCluster = null;
	
	private LinkedList<Integer> serverIDList = null;
	
	private Queue<IJob> jobQueue = null;
	
	private Comparator<Integer> compareServer = null;
	
	public JobHandler2(Boolean running,IServerClusterUsageData sC_UsageData,IServerCluster sC)
	{
		this.running = running;
		this.sC_UsageData = sC_UsageData;
		this.serverCluster = sC;
		
		jobQueue = new LinkedList<IJob>();
		serverIDList = new LinkedList<Integer>();
		
		compareServer = new ServerComparator2(serverCluster,sC_UsageData);
	}
	
	public void run() 
	{
		while(running)
		{
			if(!jobQueue.isEmpty())
			{
				// Schedule the first job in the queue
				
				refreshServerList();
				
				if(!serverIDList.isEmpty())
					scheduleJob();
			}
			
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public void jobIn(IJob newJob) 
	{
		jobQueue.offer(newJob);
		
		System.out.println("New Job added into handler");
	}
	
	private void scheduleJob()
	{
		// Assign the job to the first i.e the least power consuming server
		
		IJob currentJob = jobQueue.peek();
		
		if(currentJob != null)
		{
			for(int i=0;i<serverIDList.size();i++)
			{
				if(serverCluster.getServer(serverIDList.get(i).intValue()).getTotalNPEValue() >= currentJob.getNPE())
				{
					serverCluster.getServer(serverIDList.get(i).intValue()).assignJob(currentJob);
					jobQueue.poll();
					
					System.out.println("Job Handled !!");
					
					break;
				}
			}
		}
	}
	
	private void refreshServerList()
	{
		serverIDList.clear();
		
		for(int i=0;i<serverCluster.getServerCount();i++)
			serverIDList.add(new Integer(serverCluster.getServer(i).getServerID()));
		
		Collections.sort(serverIDList,compareServer);
	}
}
